<template>
  <div class="comment-list">
    <!-- <div class="comment-header">
      <h4>评论 ({{ comments.length }})</h4>
    </div> -->

    <div class="comment-items">
      <div v-for="comment in comments" :key="comment.id" class="comment-item">
        <div class="comment-avatar">
          <img :src="getUserAvatar(comment)" :alt="getUserName(comment)" />
        </div>

        <div class="comment-content">
          <div class="comment-header-info">
            <span class="comment-user">{{ getUserName(comment) }}</span>
            <span class="comment-time">{{
              formatTime(comment.createTime)
            }}</span>
          </div>

          <div class="comment-text" v-html="getCommentText(comment)"></div>

          <div class="comment-actions">
            <button class="action-btn" @click="handleReply(comment)">
              回复
            </button>
            <!-- <button class="action-btn" @click="handleLike(comment)">点赞</button> -->
            <button
              class="action-btn delete"
              @click="handleDelete(comment)"
              v-if="canDelete(comment)"
            >
              删除
            </button>
          </div>

          <!-- 回复列表 -->
          <div
            v-if="comment.replies && comment.replies.length > 0"
            class="replies"
          >
            <div
              v-for="reply in comment.replies"
              :key="reply.id"
              class="reply-item"
            >
              <div class="reply-avatar">
                <img :src="getUserAvatar(reply)" :alt="getUserName(reply)" />
              </div>

              <div class="reply-content">
                <div class="reply-header">
                  <span class="reply-user">{{ getUserName(reply) }}</span>
                  <span class="reply-time">{{
                    formatTime(reply.createTime)
                  }}</span>
                </div>

                <div class="reply-text" v-html="getCommentText(reply)"></div>

                <div class="reply-actions">
                  <button class="action-btn" @click="handleReply(reply)">
                    回复
                  </button>
                  <button
                    class="action-btn delete"
                    @click="handleDelete(reply)"
                    v-if="canDelete(reply)"
                  >
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="comments.length === 0" class="empty-state">
      <p>暂无评论，快来发表第一条评论吧！</p>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import type { CommentVo } from "@/interface/project";
  import { ref, onMounted, watch } from "vue";

  // 定义组件属性
  interface Props {
    recordId: string;
    commentList: CommentVo[];
  }

  const props = defineProps<Props>();

  // 定义组件事件
  const emit = defineEmits<{
    reply: [comment: CommentVo];
    delete: [comment: CommentVo];
    like: [comment: CommentVo];
  }>();

  // 响应式数据
  const comments = ref<CommentVo[]>([]);
  const defaultAvatar =
    "https://api.dicebear.com/7.x/avataaars/svg?seed=default";
  const currentUser = ref({
    id: "current-user-123",
    name: "当前用户",
  });

  // 获取用户头像
  const getUserAvatar = (comment: CommentVo) => {
    const userName = comment.creatorName || comment.modifierName || "User";
    return `https://api.dicebear.com/7.x/avataaars/svg?seed=${userName}`;
  };

  // 获取用户名
  const getUserName = (comment: CommentVo) => {
    return comment.creatorName || comment.modifierName || "未知用户";
  };

  // 获取评论内容
  const getCommentText = (comment: CommentVo) => {
    return comment.text || "暂无内容";
  };

  // 格式化时间
  const formatTime = (time: Date | string | undefined) => {
    if (!time) return "";

    const timeObj = time instanceof Date ? time : new Date(time);
    const now = new Date();
    const diff = now.getTime() - timeObj.getTime();

    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (minutes < 1) {
      return "刚刚";
    } else if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 30) {
      return `${days}天前`;
    } else {
      return timeObj.toLocaleDateString("zh-CN");
    }
  };

  // 处理回复
  const handleReply = (comment: CommentVo) => {
    emit("reply", comment);
  };

  // 处理删除
  const handleDelete = (comment: CommentVo) => {
    emit("delete", comment);
  };

  // 处理点赞
  const handleLike = (comment: CommentVo) => {
    emit("like", comment);
  };

  // 判断是否可以删除
  const canDelete = (comment: CommentVo) => {
    return (
      comment.creator === currentUser.value.id ||
      comment.modifier === currentUser.value.id
    );
  };

  // 添加新评论到列表
  const addComment = (newComment: CommentVo) => {
    comments.value.unshift(newComment);
  };

  // 添加回复到指定评论
  const addReply = (commentId: string, reply: CommentVo) => {
    const comment = comments.value.find((c) => c.id === commentId);
    if (comment) {
      if (!comment.replies) {
        comment.replies = [];
      }
      comment.replies.push(reply);
    }
  };

  // 删除评论
  const removeComment = (commentId: string) => {
    const index = comments.value.findIndex((c) => c.id === commentId);
    if (index > -1) {
      comments.value.splice(index, 1);
    } else {
      // 查找回复中的评论
      comments.value.forEach((comment) => {
        if (comment.replies) {
          const replyIndex = comment.replies.findIndex(
            (r: CommentVo) => r.id === commentId,
          );
          if (replyIndex > -1) {
            comment.replies.splice(replyIndex, 1);
          }
        }
      });
    }
  };

  // 监听 commentList 变化
  watch(
    () => props.commentList,
    (newCommentList) => {
      if (newCommentList && newCommentList.length > 0) {
        comments.value = newCommentList;
      }
    },
    { immediate: true },
  );

  // 组件挂载时加载数据
  onMounted(() => {
    // 使用传入的 commentList 数据
    if (props.commentList && props.commentList.length > 0) {
      comments.value = props.commentList;
    }
  });

  // 暴露方法给父组件
  defineExpose({
    addComment,
    addReply,
    removeComment,
  });
</script>

<style lang="scss" scoped>
  .comment-list {
    background: #fff;

    .comment-header {
      padding: 16px 20px 12px;
      border-bottom: 1px solid #f0f0f0;

      h4 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }

    .comment-items {
      padding: 0 20px;

      .comment-item {
        display: flex;
        padding: 16px 0;
        border-bottom: 1px solid #f5f5f5;

        &:last-child {
          border-bottom: none;
        }

        .comment-avatar {
          margin-right: 12px;

          img {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            object-fit: cover;
          }
        }

        .comment-content {
          flex: 1;
          min-width: 0;

          .comment-header-info {
            display: flex;
            align-items: center;
            margin-bottom: 6px;

            .comment-user {
              font-size: 14px;
              font-weight: 500;
              color: #333;
              margin-right: 8px;
            }

            .comment-time {
              font-size: 12px;
              color: #999;
            }
          }

          .comment-text {
            font-size: 14px;
            color: #666;
            line-height: 1.5;
            margin-bottom: 8px;
            word-wrap: break-word;

            :deep(strong) {
              font-weight: 600;
              color: #333;
            }

            :deep(ul) {
              margin: 8px 0;
              padding-left: 20px;
            }

            :deep(li) {
              margin: 4px 0;
            }
          }

          .comment-actions {
            display: flex;
            gap: 16px;

            .action-btn {
              background: none;
              border: none;
              color: #999;
              font-size: 12px;
              cursor: pointer;
              padding: 0;

              &:hover {
                color: #1890ff;
              }

              &.delete {
                &:hover {
                  color: #ff4d4f;
                }
              }
            }
          }

          .replies {
            margin-top: 12px;
            padding-left: 12px;
            border-left: 2px solid #f0f0f0;

            .reply-item {
              display: flex;
              padding: 8px 0;

              .reply-avatar {
                margin-right: 8px;

                img {
                  width: 24px;
                  height: 24px;
                  border-radius: 50%;
                  object-fit: cover;
                }
              }

              .reply-content {
                flex: 1;
                min-width: 0;

                .reply-header {
                  display: flex;
                  align-items: center;
                  margin-bottom: 4px;

                  .reply-user {
                    font-size: 13px;
                    font-weight: 500;
                    color: #333;
                    margin-right: 6px;
                  }

                  .reply-time {
                    font-size: 11px;
                    color: #999;
                  }
                }

                .reply-text {
                  font-size: 13px;
                  color: #666;
                  line-height: 1.4;
                  margin-bottom: 6px;
                  word-wrap: break-word;
                }

                .reply-actions {
                  display: flex;
                  gap: 12px;

                  .action-btn {
                    background: none;
                    border: none;
                    color: #999;
                    font-size: 11px;
                    cursor: pointer;
                    padding: 0;

                    &:hover {
                      color: #1890ff;
                    }

                    &.delete {
                      &:hover {
                        color: #ff4d4f;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    .empty-state {
      text-align: center;
      padding: 60px 20px;
      color: #999;

      p {
        margin: 0;
        font-size: 14px;
      }
    }
  }
</style>
